package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {

    @Autowired
    private DeptService deptService;

    @Autowired
    private EmpExprService empExprService;


    @Override
    public PageResult getPageResult(EmpQueryParam param) {
        // 设置分页参数
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        // 排序
        page.addOrder(OrderItem.desc("update_time"));

        // LamdbaQueryWrapper
       /* LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(param.getName()!=null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender()!=null, Emp::getGender, param.getGender())
                .between(param.getBegin()!=null && param.getEnd()!=null, Emp::getEntryDate, param.getBegin(),param.getEnd());
      page=page(page,queryWrapper);
*/

      page=   lambdaQuery().like(param.getName()!=null && !param.getName().isEmpty(), Emp::getName, param.getName())
                 .eq(param.getGender()!=null, Emp::getGender, param.getGender())
                 .between(param.getBegin()!=null && param.getEnd()!=null, Emp::getEntryDate, param.getBegin(),param.getEnd())
                 .page(page);



        // 查询到的员工数据
        List<Emp> emps = page.getRecords();
        List<Integer> deptIds = emps.stream().map(emp -> {
            return emp.getDeptId();
        }).toList();

        if(!deptIds.isEmpty()){
            // 根据部门ID查询部门名称
            List<Dept> depts = deptService.listByIds(deptIds);
            emps.forEach(emp -> {
                depts.forEach(dept -> {
                    if (emp.getDeptId()!=null && emp.getDeptId().equals(dept.getId())) {
                        emp.setDeptName(dept.getName());
                    }
                });
            });
        }


        // 封装分页结果
        return  new PageResult<Emp>(page.getTotal(),emps);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        // 保存员工信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        save(emp);
        //保存员工工作经历信息
        List<EmpExpr> exprList = emp.getExprList();

        // 设置员工ID
        exprList.forEach(expr -> {
            expr.setEmpId(emp.getId());
        });

        // 批量保存工作经历信息
        empExprService.saveBatch(exprList);

    }

    @Override
    public Emp getEmpById(Integer id) {

        // 查询员工信息
        Emp emp = getById(id);

        //查询员工工作经历信息
        LambdaQueryWrapper<EmpExpr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EmpExpr::getEmpId, id);
        List<EmpExpr> exprs = empExprService.list(wrapper);
        emp.setExprList(exprs);

        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        // 更新员工信息
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);

        // 更新员工工作经历信息
        // 先删除
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        // 后新增
        List<EmpExpr> exprList = emp.getExprList();
        if (!exprList.isEmpty()) {
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprService.saveBatch(exprList);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeEmpByIds(List<Integer> ids) {
        // 批量删除 员工信息
        removeBatchByIds(ids);

        // 批量删除员工工作经历信息
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));

    }
}
